package cn.xxc.user.service.impl;

import cn.xxc.basic.exception.BusinessException;
import cn.xxc.basic.util.Md5Utils;
import cn.xxc.basic.util.StrUtils;
import cn.xxc.org.domain.Shop;
import cn.xxc.user.domain.Logininfo;
import cn.xxc.user.domain.User;
import cn.xxc.user.dto.UserDto;
import cn.xxc.user.mapper.LogininfoMapper;
import cn.xxc.user.mapper.UserMapper;
import cn.xxc.user.service.ILogininfoService;
import cn.xxc.user.service.IUserService;
import cn.xxc.basic.service.impl.BaseServiceImpl;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;

import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;
import java.util.Map;

/**
 * 业务实现类：
 * 1.电话注册
 * 2.邮箱注册
 */
@Service
public class UserServiceImpl extends BaseServiceImpl<User> implements IUserService {
    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private LogininfoMapper logininfoMapper;
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private JavaMailSender javaMailSender;

    /**
     * 电话注册
     * @param userDto
     */
    @Override
    @Transactional
    public void phoneRegister(UserDto userDto) {
        String phone = userDto.getPhone();
        String phoneCode = userDto.getPhoneCode();
        String password = userDto.getPassword();
        String passwordRepeat = userDto.getPasswordRepeat();
        //一：校验：空值校验
        if(StringUtils.isEmpty(phone) || StringUtils.isEmpty(phoneCode)
                ||StringUtils.isEmpty(password) || StringUtils.isEmpty(passwordRepeat)){
            throw new BusinessException("信息不能为空!!!");
        }
        //二：校验：密码是否一致
        if(!password.equals(passwordRepeat)){
            throw new BusinessException("两次密码不一致");
        }
        //三：手机验证码：是否过期，是否正确
        Object redisPhoneCode = redisTemplate.opsForValue().get("register:" + phone);
        if(redisPhoneCode == null){
            throw new BusinessException("手机验证码过期，请重新获取!!!");
        }
        if(!phoneCode.equals(redisPhoneCode.toString().split(":")[0])){  // code:时间戳
            throw new BusinessException("手机验证码错误!!!");
        }
        //四：添加到数据库
        User user = userDto1User(userDto);
        Logininfo logininfo = user1Logininfo(user);
        //1.先添加logininfo信息 - 自增ID
        logininfoMapper.save(logininfo);
        //2.再将自增ID设置到user中吗，再添加user表
        user.setLogininfoId(logininfo.getId());
        userMapper.save(user);
    }

    private Logininfo user1Logininfo(User user){
        Logininfo logininfo = new Logininfo();
        //按照属性同名原则进行属性拷贝【username，email，phone，salt，password】
        BeanUtils.copyProperties(user,logininfo); //底层原理就是通过getter,setter方法实现
        logininfo.setType(1);//用户手机验证码注册
        logininfo.setDisable(true);//手机验证码注册成功就可以直接使用
        return logininfo;
    }

    private User userDto1User(UserDto userDto) { //phone ,password
        User user = new User();
        user.setUsername(userDto.getPhone());
        user.setPhone(userDto.getPhone());
        //生成随机盐值
        String salt = StrUtils.getComplexRandomString(32);
        //用MD5加密加盐
        String md5Pwd = Md5Utils.encrypByMd5(userDto.getPassword() + salt);
        user.setSalt(salt);
        user.setPassword(md5Pwd);
        user.setState(1);
        return user;
    }

    /**
     * 邮箱注册
     * @param userDto
     * @throws MessagingException
     */
    @Override
    @Transactional
    public void emailRegister(UserDto userDto) throws MessagingException {
        String email = userDto.getEmail();
        String password = userDto.getPassword();
        String passwordRepeat = userDto.getPasswordRepeat();
        //一：校验：空值校验
        if(StringUtils.isEmpty(email)
           ||StringUtils.isEmpty(password)
           || StringUtils.isEmpty(passwordRepeat)){
            throw new BusinessException("信息不能为空!!!");
        }
        //二：校验：密码是否一致
        if(!password.equals(passwordRepeat)){
            throw new BusinessException("两次密码不一致");
        }
        //三：校验：email是否已存在
        User u1=userMapper.findByEmail(email);
        if (u1!=null){
            throw new BusinessException("email已存在");
        }
        //四：添加到数据库
        User user = userDto2User(userDto);
        Logininfo logininfo = user2Logininfo(user);
        //1.先添加logininfo信息 - 自增ID
        logininfoMapper.save(logininfo);
        //2.再将自增ID设置到user中吗，再添加user表
        user.setLogininfoId(logininfo.getId());
        userMapper.save(user);

        //五：发邮件激活
        MimeMessage mimeMessage = javaMailSender.createMimeMessage();
        MimeMessageHelper helper = new MimeMessageHelper(mimeMessage, true, "utf-8");

        helper.setFrom("2933487123@qq.com");
        helper.setSubject("账号激活邮件");
        //true - 能够再内容中编写html标签 - 会解析
        helper.setText("<h3>你的账号已经通过，请<a href='http://127.0.0.1:8080/user/active/"+user.getId()
                +"'>点击这里</a>激活账号</h3>", true);
        //helper.setTo("logininfo.getEmail()");
        helper.setTo("2933487123@qq.com");
        //发送
        javaMailSender.send(mimeMessage);
    }

    private Logininfo user2Logininfo(User user){
        Logininfo logininfo = new Logininfo();
        //按照属性同名原则进行属性拷贝【username，email，phone，salt，password】
        BeanUtils.copyProperties(user,logininfo); //底层原理就是通过getter,setter方法实现
        logininfo.setType(1);//用户手注册
        logininfo.setDisable(false);//  是否启用
        return logininfo;
    }

    private User userDto2User(UserDto userDto) { //phone ,password
        User user = new User();
        user.setUsername(userDto.getEmail());
        user.setEmail(userDto.getEmail());
        //生成随机盐值
        String salt = StrUtils.getComplexRandomString(32);
        //用MD5加密加盐
        String md5Pwd = Md5Utils.encrypByMd5(userDto.getPassword() + salt);
        user.setSalt(salt);
        user.setPassword(md5Pwd);
        user.setState(0);//1  为启用  0   为禁用
        return user;
    }

    /**
     * 修改用户的使用状态
     * @param user
     */
    @Override
    @Transactional
    public void update(User user) {
        super.update(user);
        Logininfo logininfo = logininfoMapper.loadByid(user.getLogininfoId());
        logininfo.setDisable(false);
        logininfoMapper.update(logininfo);
    }
}
